package com.baizan.daka.glide

import java.io.IOException
import java.security.GeneralSecurityException
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*

class SSLSocketClient {
    //获取这个SSLSocketFactory
    companion object {
        private var TRUSTED_VERIFIER: HostnameVerifier? = null
        private var TRUSTED_FACTORY: SSLSocketFactory? = null


        @Throws(GeneralSecurityException::class)
         fun getTrustedFactory(): SSLSocketFactory? {
            if (TRUSTED_FACTORY == null) {
                val trustAllCerts =
                    arrayOf<TrustManager>(object : X509TrustManager {
                        override fun getAcceptedIssuers(): Array<X509Certificate?>? {
                            return arrayOfNulls(0)
                        }

                        override fun checkClientTrusted(
                            chain: Array<X509Certificate?>?,
                            authType: String?
                        ) {
                        }

                        override fun checkServerTrusted(
                            chain: Array<X509Certificate?>?,
                            authType: String?
                        ) {
                        }
                    })
                try {
                    val context = SSLContext.getInstance("TLS")
                    context.init(null, trustAllCerts, SecureRandom())
                    TRUSTED_FACTORY = context.socketFactory
                } catch (e: GeneralSecurityException) {
                    val ioException = IOException(
                        "Security exception configuring SSL context"
                    )
                    ioException.initCause(e)
                    throw e
                }
            }
            return TRUSTED_FACTORY
        }

         fun getTrustedVerifier(): HostnameVerifier? {
            if (TRUSTED_VERIFIER == null) TRUSTED_VERIFIER =
                HostnameVerifier { hostname, session -> true }
            return TRUSTED_VERIFIER
        }
    }

}